import axios from "axios"
import debounce from "@u/debounce"
import render from "@u/render"

import "./siteHeader.scss"


export default (() => {

    let siteHeader = document.createElement("div")

    siteHeader.classList.add("site-header");

    (async () => {

        // 请求数据
        const res = await axios.get("http://localhost:9000/api/siteheader");

        const { search_data, nav_data, nav_drop_data } = res.data;

        siteHeader.innerHTML = render(
            {
                nav_data,
                search_data,
                nav_drop_data
            },
            {
                nav_data: `<li productid={{item.productId}}><a productid="{{item.productId}}" href="javascript:void(0)">{{item.text}}</a></li>`,
                search_data: `<span>{{item}}</span>`,
                nav_drop_data: (data) => {
                    return data.map(item => {
                        let temp = ``
                        temp = `<div class="item" productid="${item.productId}">`
                        temp += item.data.map(i => `<li class="slide-down-item"><a href="javascript:void(0)"><img src="${i.imgSrc}"></img><span>${i.title}</span><span>${i.price}元起</span></li></a><span class="sep"></span>`).join("")
                        temp += `</div>`
                        return temp
                    }).join("")
                }
            },
            `
            <div class="site-header-wrapper auto"><a href="//www.mi.com/index.html" class="header-logo" title="小米商城"></a>
                <nav>{{nav_data}}</nav>
                <div class="header-search">
                    <form id="search" class="search-form" action="//search.mi.com/search">
                        <input type="text" name="keyword" id="keyword" placeholder="小米手机">
                        <div class="search-drop">{{search_data}}</div>
                        <i class="iconfont icon-search"></i>
                    </form>
                </div>
            </div>
            <div class="nav-slide-down">
                <div class="nav-slide-down-wrapper auto">
                      {{nav_drop_data}}
                </div>
            </div>
            `)


        const searchDrop = siteHeader.querySelector(".search-drop")
        const keyword = siteHeader.querySelector("#keyword")
        const iconSearch = siteHeader.querySelector(".icon-search")

        const navSlideDown = siteHeader.querySelector(".nav-slide-down")
        const search = siteHeader.querySelector(".header-search")
        const nav = siteHeader.querySelector(".site-header nav");
        const navLis = [...nav.querySelectorAll("li")].slice(0, -2)

        let preActiveItem = null
        let currentSiteHeaderWrapper = null
        let currentHeader = null

        const hd = debounce(function () {
            if (!navSlideDown.classList.contains("active")) return
            navSlideDown.style.height = 0;
            setTimeout(() => {
                navSlideDown.classList.remove("active")
            }, 300)
        }, 300)

        const sd = debounce(function () {
            if (navSlideDown.classList.contains("active")) return
            // console.log("show");
            navSlideDown.classList.add("active")
            navSlideDown.style.height = '230px'
        }, 300)

        // 计算nav的边界
        const caculateNavoffSetValue = _ => {
            if (!currentSiteHeaderWrapper) {
                currentSiteHeaderWrapper = siteHeader.querySelector(".site-header-wrapper")
            }
            if (!currentHeader) {
                currentHeader = document.querySelector("header")
            }
            const offsetLeft = currentSiteHeaderWrapper.offsetLeft + nav.offsetLeft
            // 去掉最后两个li
            const wid = [...nav.children].splice(-2, 2).reduce((pre, cur) => pre + cur.clientWidth, 0)
            const offsetTop = nav.offsetTop + currentHeader.clientHeight
            return { minX: offsetLeft, maxX: offsetLeft + nav.clientWidth - wid, minY: offsetTop + 10, maxY: offsetTop + nav.clientHeight }
        }

        // 处理每个nav下的li 所对应的 下拉item列表
        const handleActiveItem = function () {

            const id = this.getAttribute("productId")

            let newItem = [...navSlideDown.querySelectorAll(".item")].filter(i => i.getAttribute("productid") === id)

            newItem = newItem.length > 0 ? newItem[0] : null;

            if (!newItem) return

            if (preActiveItem) preActiveItem.style.display = 'none'

            newItem.style.display = 'flex'

            preActiveItem = newItem
        }

        const showSearchDrop = () => {
            keyword.classList.add("active")
            searchDrop.style.display = 'flex'
            iconSearch.classList.add("active")
        }

        const hideSearchDrop = () => {
            searchDrop.style.display = 'none'
            keyword.classList.remove("active")
            iconSearch.classList.remove("active")
        }

        // 处理事件
        (_ => {

            // 处理搜索框的点击事件
            search.addEventListener("click", function (e) {
                showSearchDrop()
            })

            search.addEventListener("mouseleave", function (e) {
                hideSearchDrop()
            })

            let obj = null

            navLis.forEach(li => {
                li.addEventListener("mouseenter", function (e) {
                    const { target } = e
                    sd()
                    handleActiveItem.call(target)
                })
            })

            nav.addEventListener("mouseover", debounce(function (e) {
                const { target } = e
                if (!obj) obj = caculateNavoffSetValue();
                const { maxX, maxY, minY, minX } = obj
                if (!(e.pageX >= minX - 2 && e.pageX <= maxX - 2) || !(e.pageY <= maxY && e.pageY >= minY)) hd()
                handleActiveItem.call(target)
            }, 250))

            nav.addEventListener("mouseleave", function (e) {
                if (!obj) obj = caculateNavoffSetValue();
                const { maxY } = obj
                if (e.pageY < maxY) hd()
            })

            navSlideDown.addEventListener("mouseleave", function (e) {
                if (!obj) obj = caculateNavoffSetValue();
                const { maxY } = obj
                if (e.pageY > maxY + navSlideDown.clientHeight) hd()
            })

        })()
    })()

    return siteHeader
})()